package com.foreveross.fetl.queue;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.foreveross.fetl.application.IExchangeRateApplication;
import com.foreveross.fetl.common.vo.PereMoreData;
import com.foreveross.fetl.queue.util.LogMessageUtils;
import com.foreveross.fetl.util.DateUtils;
import com.foreveross.fetl.util.JsonUtil;
import com.foreveross.fetl.util.StringUtils;
import com.foreveross.fetl.vo.ExchangeRateVO;
@Component
public class PereMoreDataPreprocess {

	private static Logger log = Logger.getLogger("pereMoreData");
	
	@Inject
	private IExchangeRateApplication exchangeRateApplication;
	
	private int tasksNumber;//任务数 多少条rowkey
	
	private int failuresNumber;//失败数
	
	private int insertNumber; //插入条数 
	
	private long excuteStartTime;
	
	private String taskTime=null;
	
	/**
	 * 定时方法
	 */
	public void execute() {
		rollBackNumber();
		taskTime=DateUtils.format(new Date(), "yyyy-MM-dd HH");
		process();
		LogMessageUtils.build("汇率抓取入库", this.getClass().getSimpleName(), 2, null, 
				failuresNumber, tasksNumber, insertNumber, taskTime, excuteStartTime);
	}
	
	
	private void process() {
		List<PereMoreData> listPereMoreData =null;
		List<ExchangeRateVO> listVO =new ArrayList<ExchangeRateVO>();
		for(int i=0;i<3;i++){
			//如果抓取失败就重复抓取直到抓取3次
			try {
				listPereMoreData=this.fetch();
			} catch (Exception e) {
				log.error(i);
				log.error(StringUtils.getStackTrace(e));
			}
			if(null!=listPereMoreData && listPereMoreData.size()>0){
				break;
			}
		}
		if(null!=listPereMoreData && listPereMoreData.size()>0){
			for(PereMoreData pereMoreData :listPereMoreData){
				ExchangeRateVO vo =new ExchangeRateVO();
				vo.setCode(pereMoreData.getCode());
				vo.setName(pereMoreData.getCurrency());
				vo.setRefePrice(pereMoreData.getRefePrice()/100);
				vo.setDate(DateUtils.format(new Date(), "yyyyMMdd"));
				vo.setLastTime(new Date());
				listVO.add(vo);
			}
			for(ExchangeRateVO vo :listVO){
				tasksNumber++;
				try {
					this.saveExchangeRate(vo);
					insertNumber++;
				} catch (Exception e) {
					log.error(StringUtils.getStackTrace(e));
					failuresNumber++;
				}
			}
		}
	
				
		
		
	}
	
	private void saveExchangeRate(ExchangeRateVO vo) {
		if(null==vo) return ;
		List<ExchangeRateVO> oldList =exchangeRateApplication.findByCondition(vo.getName(), vo.getCode(),  vo.getDate());
		if(null!=oldList && oldList.size()>0){
			vo.setId(oldList.get(0).getId());
		}
		exchangeRateApplication.save(vo);
	}


	//从网页里抓取汇率
	public List<PereMoreData> fetch() throws Exception {
		HttpClient client;
		HttpGet get;
		String page;
		List<PereMoreData> list =null;
		try {
			client=new DefaultHttpClient();//第一次全新的抓取
			client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 50000);
			client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,  50000);
			String url = "http://data.bank.hexun.com/other/cms/fxjhjson.ashx?callback=PereMoreData";
			get = new HttpGet(url);
			get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:28.0) Gecko/20100101 Firefox/28.0");
			get.addHeader("Host", "data.bank.hexun.com");
			get.addHeader("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			get.addHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
			HttpEntity entity=client.execute(get).getEntity();
			page = EntityUtils.toString(entity, "gb2312");
			String json =page.substring(page.indexOf("(")+1,page.indexOf(")")).replace(" ", "");
			list =JsonUtil.getDTOList(json, PereMoreData.class);
		} finally {
			get = null;
			client = null;
		}
		return list;
	}

	/**
	 * 重置
	 */
	public void  rollBackNumber(){
		tasksNumber=0;
		failuresNumber=0;
		insertNumber=0;
		excuteStartTime = System.currentTimeMillis();
		LogMessageUtils.create("汇率抓取入库", this.getClass().getSimpleName());
	}

}
